package com.species.web.wechat.miniapp.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaMessage;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
import com.species.web.wechat.miniapp.config.WxMiniAppConfig;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2020/7/20 10:46
 */
@RestController
@RequestMapping("/api/wechat/{appid}")
@Slf4j
public class WxPortalController {

    private static final DateTimeFormatter formatter =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@PathVariable String appid,
                          @RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {
        log.info("\n接收到来自微信服务器的认证消息：signature = [{}], timestamp = [{}], nonce = [{}], echostr = [{}]",
                signature, timestamp, nonce, echostr);

        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }

        final WxMaService wxService = WxMiniAppConfig.getMaService(appid);

        if (wxService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }

        return "非法请求";
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable String appid,
                       @RequestBody String requestBody,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature,
                       @RequestParam(name = "encrypt_type", required = false) String encryptType,
                       @RequestParam(name = "signature", required = false) String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce) {
        log.info("\n接收微信请求：[msg_signature=[{}], encrypt_type=[{}], signature=[{}]," +
                        " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                msgSignature, encryptType, signature, timestamp, nonce, requestBody);

        final WxMaService wxService = WxMiniAppConfig.getMaService(appid);

        final boolean isJson = Objects.equals(wxService.getWxMaConfig().getMsgDataFormat(),
                WxMaConstants.MsgDataFormat.JSON);
        if (StringUtils.isBlank(encryptType)) {
            // 明文传输的消息
            WxMaMessage inMessage;
            if (isJson) {
                inMessage = WxMaMessage.fromJson(requestBody);
            } else {//xml
                inMessage = WxMaMessage.fromXml(requestBody);
            }

            this.route(inMessage, appid);
            return "success";
        }

        if ("aes".equals(encryptType)) {
            // 是aes加密的消息
            WxMaMessage inMessage;
            if (isJson) {
                inMessage = WxMaMessage.fromEncryptedJson(requestBody, wxService.getWxMaConfig());
            } else {//xml
                inMessage = WxMaMessage.fromEncryptedXml(requestBody, wxService.getWxMaConfig(),
                        timestamp, nonce, msgSignature);
            }

            this.route(inMessage, appid);
            return "success";
        }

        throw new RuntimeException("不可识别的加密类型：" + encryptType);
    }

    private void route(WxMaMessage message, String appid) {
        try {
            WxMiniAppConfig.getRouter(appid).route(message);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

//    @GetMapping("/sendmsg")
//    public void sendSubMessage() {
//
//        Member user = UserUtils.getUser();
//
//        final WxMaService wxMaService = WxMiniAppConfig.getMaService("wx9e7acf12fa7f5eb4");
//        WxMaSubscribeMessage message = new WxMaSubscribeMessage();
//        message.setTemplateId("XtxPB0QAWcWZP2iLosThiM4L6ahcjriFSZ06c-0dvjc");
//        message.setToUser("oy9Ia42-lMY_WKk_feCA2fW2w-rE");
//        message.setPage("www.baidu.com");
//        message.setLang(WxMaConstants.MiniprogramLang.ZH_CN);
//        message.setMiniprogramState(WxMaConstants.MiniprogramState.FORMAL);
//        message.addData(new WxMaSubscribeMessage.Data("name1",user.getNickname()));
//        message.addData(new WxMaSubscribeMessage.Data("phone_number2",user.getMobile()));
//        message.addData(new WxMaSubscribeMessage.Data("time3", formatter.format(LocalDateTime.now())));
//        message.addData(new WxMaSubscribeMessage.Data("phrase5","预约成功"));
//        message.addData(new WxMaSubscribeMessage.Data("thing8","遐享会员服务"));
//        try {
//            wxMaService.getMsgService().sendSubscribeMsg(message);
//        } catch (WxErrorException e) {
//            e.printStackTrace();
//        }
//    }

}
